<template>
  <div class="simple-upload-container">
    <el-upload
      class="el-upload-demo"
      :action="uploadUrl"
       name="file"
      :headers="headers"
      :multiple="false"

      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar"
    >
      <!-- 简化按钮 -->
      <el-button type="primary" size="small">
        选择资料上传
      </el-button>

      <!-- 拖拽区域（无图标版） -->
      <div class="drag-placeholder" slot="dragger">
        <p>将文件拖到此处上传</p>
        <p class="el-upload__tip">支持 PDF、Word、Excel、TXT、ZIP 等格式</p>
      </div>
    </el-upload>

    <!-- 进度条 -->
    <div v-if="uploading" class="progress-box">
      <el-progress :percentage="progress" status="active" />
      <p class="progress-text">上传进度: {{ progress }}%</p>
    </div>

    <!-- 结果提示 -->
    <div v-if="uploadResult" class="result-box">
      <el-alert
        :title="uploadResult.code === 200 ? '上传成功' : '上传失败'"
        :type="uploadResult.code === 200 ? 'success' : 'error'"
        :closable="false"
      />
      <div v-if="uploadResult.code === 200" class="file-info">
        <p><span>原始文件名:</span> {{ uploadResult.data.originalName }}</p>
        <p><span>保存名称:</span> {{ uploadResult.data.savedName }}</p>
        <p><span>文件大小:</span> {{ formatFileSize(uploadResult.data.size) }}</p>
      </div>
    </div>



      <el-card class="box-card" shadow="never">

        <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">

          <el-table-column prop="filename" label="文件名称" width="300" />
          <el-table-column prop="path" label="路径"   width="300" />
          <el-table-column prop="size" label="大小" />
          <el-table-column prop="mtime" label="时间" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                size="small"
                @click="handleDownload(scope.$index, scope.row.filename)"
                plain
                type="success"
              >下载</el-button
              >

              <el-button
                size="small"
                type="danger"
                plain
                @click="handleDelete(scope.$index, scope.row.filename)"
              >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Const  from '@/utils/const.js'
import request from '@/utils/request.js'
import { ElMessage, ElMessageBox } from 'element-plus'


// 配置项
const uploadUrl = Const.baseURL+'/admin/uploadResource'; // 后端接口地址
const token = localStorage.getItem(Const.ACCESS_TOKEN) || ''; // 示例：从本地存储获取Token
const headers = computed(() => ({ 'X-Custom-Token': token }));

// 状态管理
const uploading = ref(false);
const progress = ref(0);
const uploadResult = ref(null);

// 上传前校验
const beforeUpload = (file) => {
  const allowedTypes = [
    'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/plain'
  ];

  if (!allowedTypes.includes(file.type)) {
    alert('不支持的文件类型，请上传PDF/Word/Excel/TXT等格式');
    return false;
  }

  if (file.size > 1024 * 1024 * 50) { // 50MB限制
    alert('文件大小超过限制（最大50MB）');
    return false;
  }

  uploading.value = true;
  progress.value = 0;
  return true;
};

// 上传成功处理
const handleSuccess = (response) => {
  uploadResult.value = response;
  uploading.value = false;
};

// 上传失败处理
const handleError = (error) => {
  console.error('上传失败:', error);
  uploadResult.value = { code: 500, message: '上传失败，请重试' };
  uploading.value = false;
};

// 进度更新
const handleProgress = (event) => {
  progress.value = event.percent;
};


const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
};





const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex === 1) {
    return 'warning-row'
  } else if (rowIndex === 3) {
    return 'success-row'
  }
  return ''
}

const tableData = ref([])

const getScreenshotsPageList = () => {
  request(`/admin/resources`).then((data) => {
    tableData.value = data
  })
}

onMounted(() => {
  getScreenshotsPageList()
})



const editPageRef = ref(null)


/**
 * 删除
 * @param index
 * @param id
 */
const handleDelete = (index, filename) => {
  ElMessageBox.confirm('确认要删除这个文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request(`/admin/delete/file/${filename}`, {}, 'DELETE').then(() => {
      ElMessage.success('删除操作成功')
      getScreenshotsPageList()
    })
  })
}

/**
 * 下载
 * @param index
 * @param id
 */
const handleDownload = async (index, fileName) => {

  fetch(Const.baseURL+'/admin/download/file/'+fileName, {
    method: 'GET',
    headers: {
      'X-Custom-Token': localStorage.getItem(Const.ACCESS_TOKEN)
    }
  })
    .then(response => {
      if (!response.ok) throw new Error('下载失败');
      return response.blob(); // 处理二进制文件流
    })
    .then(blob => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName; // 指定下载文件名
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url); // 释放URL对象
    })
    .catch(error => console.error('下载错误:', error));

}



</script>

<style scoped>
.simple-upload-container {
  max-width: 100%;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.el-upload {
  width: 100%;
}

.drag-placeholder {
  margin-top: 15px;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

.progress-box {
  margin: 20px 0;
}

.progress-text {
  text-align: center;
  color: #606266;
  margin-top: 8px;
}

.result-box {
  padding: 15px;
  border-radius: 4px;
}

.file-info {
  margin-top: 10px;
  line-height: 1.8;
  color: #606266;
}

.file-info span {
  display: inline-block;
  min-width: 100px;
  font-weight: 500;
  color: #303133;
}

.el-table .warning-row {
  --el-table-tr-bg-color: #fabdcc;
}

.el-table .success-row {
  --el-table-tr-bg-color: #8febe1;
}
</style>